<template>
  <!-- 抽屉组件 -->
  <xcmg-drawer v-model="_visible" :title="title" size="60%" hideFooter>
    <!-- 表单区域 -->
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="80px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <!-- 规则编码 -->
      <el-form-item label="规则编码" prop="rule_code">
        <xcmg-input
          v-model="ruleForm.rule_code"
          placeholder="自动生成"
          disabled
        />
      </el-form-item>

      <!-- 描述 -->
      <el-form-item label="描述" prop="description">
        <xcmg-input v-model="ruleForm.description" placeholder="请输入描述" />
      </el-form-item>

      <!-- 优先级 -->
      <el-form-item label="优先级" prop="priority">
        <el-input-number
          style="width: 100%"
          v-model="ruleForm.priority"
          :min="1"
          :max="10"
          controls-position="right"
        />
      </el-form-item>

      <!-- 是否启用 -->
      <el-form-item label="是否启用" prop="active">
        <xcmg-switch
          v-model="ruleForm.active"
          size="large"
          inline-prompt
          active-text="是"
          inactive-text="否"
        />
      </el-form-item>

      <!-- 属性类型 -->
      <el-form-item label="属性类型" prop="attrType">
        <xcmg-select
          v-model="ruleForm.attrType"
          placeholder="请选择属性类型"
          clearable
        >
          <xcmg-option
            v-for="item in attrTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </xcmg-select>
      </el-form-item>

      <!-- 属性分类 -->
      <el-form-item label="属性分类" prop="attrClassify">
        <el-tree-select
          v-model="ruleForm.attrClassify"
          :data="classifyOptions"
          :filter-node-method="filterNodeMethod"
          filterable
          :disabled="isAttrClassifyDisabled || !ruleForm.attrType"
          @node-click="handleNodeClick"
        />
      </el-form-item>

      <!-- 条件配置表格 -->
      <el-form-item
        v-if="showConditions && ruleForm.attrType"
        label="条件配置"
        prop="conditions_group"
      >
        <el-table
          :data="conditions_group"
          row-key="key"
          :span-method="conditions_groupSpanMethod"
          style="width: 100%; margin-bottom: 4px"
          :tree-props="{
            children: 'sub_conditions',
            hasChildren: 'hasChildren',
          }"
          default-expand-all
        >
          <!-- 运算符列 -->
          <el-table-column prop="key" label="运算符" width="102">
            <template #default="{ row }">
              <!-- 顶级行使用全局运算符 -->
              <el-select-v2
                v-if="!hasParent(row)"
                v-model="topLevelLogicalOperator"
                placeholder="运算符"
                :options="[
                  { value: 'and', label: 'and' },
                  { value: 'or', label: 'or' },
                ]"
                @change="updateAllTopLevelConditions()"
              />
              <div v-else></div>
            </template>
          </el-table-column>

          <!-- 二层运算符列 -->
          <el-table-column
            v-if="showLogicalOperatorColumn"
            prop="logical_operator"
            width="102"
          >
            <template #default="{ row }">
              <el-select-v2
                v-if="hasParent(row)"
                v-model="row.logical_operator"
                placeholder="运算符"
                :options="[
                  { value: 'and', label: 'and' },
                  { value: 'or', label: 'or' },
                ]"
                @change="
                  (val) => updateSubGroupConditions(getParentRow(row), val)
                "
              />
              <div v-else></div>
            </template>
          </el-table-column>

          <!-- 字段列 -->
          <el-table-column prop="field" label="字段">
            <template #default="{ row }">
              <el-select-v2
                filterable
                v-model="row.field"
                placeholder="字段"
                :options="conditionFieldOptions"
              />
            </template>
          </el-table-column>

          <!-- 运算列 -->
          <el-table-column prop="operator" label="运算">
            <template #default="{ row }">
              <el-select-v2
                v-model="row.operator"
                placeholder="运算"
                :options="getOperatorOptions(row.field, true)"
              />
            </template>
          </el-table-column>

          <!-- 值列 -->
          <el-table-column prop="value" label="值" width="202">
            <template #default="{ row }">
              <!-- 输入框：当不满足下拉条件时 -->
              <el-input
                v-show="!shouldShowSelectByOperatorAndField(row, true)"
                v-model="row.value"
                :placeholder="
                  isMultiValueOperator(row.operator)
                    ? '输入多个值英文逗号分隔'
                    : '请输入值'
                "
              />

              <!-- 下拉框：当满足下拉条件时，根据 operator 决定是否 multiple -->
              <el-select
                v-show="shouldShowSelectByOperatorAndField(row, true)"
                v-model="row.value"
                :multiple="row.operator === 'in' || row.operator === 'not in'"
                placeholder="请选择值"
                style="width: 100%"
              >
                <el-option
                  v-for="item in getValueOptions(row.field, true)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <!-- 操作列 -->
          <el-table-column label="操作" width="74">
            <template #header>
              <div style="display: flex; align-items: center">
                <span>操作</span>
                <div style="padding-left: 4px; padding-bottom: 4px">
                  <el-tooltip content="添加">
                    <svg-icon name="Regular" @click="addConditionRow(null)" />
                  </el-tooltip>
                </div>
              </div>
            </template>
            <template #default="{ row }">
              <el-button
                v-if="!hasParent(row)"
                type="primary"
                link
                @click="addConditionRow(row)"
              >
                <svg-icon name="Regular" />
              </el-button>
              <el-button
                v-if="
                  (!hasParent(row) && conditions_group.length > 1) ||
                  (hasParent(row) &&
                    getParentRow(row)?.sub_conditions?.length > 0)
                "
                type="danger"
                link
                @click="delConditionRow(row)"
              >
                <svg-icon name="Delete" />
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <!-- 结果配置表格 -->
      <el-form-item label="结果配置" prop="results">
        <el-table
          :data="results"
          row-key="key"
          :span-method="resultSpanMethod"
          style="width: 100%; margin-bottom: 4px"
          :tree-props="{
            children: 'sub_conditions',
            hasChildren: 'hasChildren',
          }"
          :default-expand-all="false"
        >
          <!-- 运算符列 -->
          <el-table-column prop="logical_operator" label="运算符" width="102">
            <template #default="{ row }">
              <el-select-v2
                v-model="resultLogicalOperator"
                placeholder="运算符"
                :options="[
                  { value: 'and', label: 'and' },
                  { value: 'or', label: 'or' },
                ]"
              />
            </template>
          </el-table-column>

          <!-- 字段列 -->
          <el-table-column prop="field" label="字段">
            <template #default="{ row }">
              <el-select-v2
                filterable
                v-model="row.field"
                :placeholder="
                  ruleForm.attrClassify ? '字段' : '请先选择属性分类'
                "
                :options="resultsFieldOptions"
              />
            </template>
          </el-table-column>

          <!-- 运算列 -->
          <el-table-column prop="operator" label="运算">
            <template #default="{ row }">
              <el-select-v2
                v-model="row.operator"
                placeholder="运算"
                :options="getOperatorOptions(row.field, false)"
              />
            </template>
          </el-table-column>

          <!-- 值列 -->
          <el-table-column prop="value" label="值" width="202">
            <template #default="{ row }">
              <!-- 输入框：当不满足下拉条件时 -->
              <el-input
                v-show="!shouldShowSelectByOperatorAndField(row, true)"
                v-model="row.value"
                :placeholder="
                  isMultiValueOperator(row.operator)
                    ? '输入多个值英文逗号分隔'
                    : '请输入值'
                "
              />

              <!-- 下拉框：当满足下拉条件时，根据 operator 决定是否 multiple -->
              <el-select
                v-show="shouldShowSelectByOperatorAndField(row, true)"
                v-model="row.value"
                :multiple="row.operator === 'in' || row.operator === 'not in'"
                placeholder="请选择值"
                style="width: 100%"
              >
                <el-option
                  v-for="item in getValueOptions(row.field, true)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column label="操作" width="74">
            <template #header>
              <div style="display: flex; align-items: center">
                <span>操作</span>
                <div style="padding-left: 4px; padding-bottom: 4px">
                  <el-tooltip content="添加">
                    <svg-icon name="Regular" @click="addResultRow(null)" />
                  </el-tooltip>
                </div>
              </div>
            </template>
            <template #default="{ row }">
              <el-button
                type="danger"
                v-if="results.length > 1"
                link
                @click="delResultRow(row)"
              >
                <svg-icon name="Delete" />
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <!-- 错误代码 -->
      <el-form-item label="错误代码" prop="error_code">
        <xcmg-input
          v-model="ruleForm.error_code"
          placeholder="请输入错误代码"
        />
      </el-form-item>

      <!-- 描述 -->
      <el-form-item label="错误信息" prop="error_message">
        <xcmg-input
          v-model="ruleForm.error_message"
          placeholder="请输入错误信息"
        />
      </el-form-item>
    </el-form>

    <!-- 抽屉底部按钮 -->
    <template #footer>
      <div class="drawer-footer">
        <el-button type="primary" @click="handleSave(ruleFormRef)"
          >保存</el-button
        >
        <el-button @click="handleSaveClose(ruleFormRef)">保存并关闭</el-button>
      </div>
    </template>
  </xcmg-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, onMounted, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { SvgIcon } from "xcmg-components";
import {
  materialRuleAdd,
  materialRuleUpdata,
  basicsLov,
  classifyLov,
  attributePoolLov,
} from "@/api/ruleBase";
import { XcmgMessage } from "xcmg-components";
import { useClassifyLovStore } from "@/store/lov";

const lovStore = useClassifyLovStore();

// 定义props
const props = defineProps<{
  title: string;
  visible: boolean;
  rowData: object;
}>();

// 定义emits
const emit = defineEmits(["update:visible", "queryMaterialRule"]);

// 计算属性控制抽屉显示/隐藏
const _visible = computed({
  get() {
    return props.visible;
  },
  set(val) {
    emit("update:visible", val);
  },
});

// 定义表格行数据类型
interface RuleTableItem {
  key: string;
  field: string;
  operator: string;
  value: string;
  logical_operator: string;
  sub_conditions?: RuleTableItem[];
}

// 定义表单数据类型
interface RuleForm {
  rule_code: string;
  description: string;
  priority: number;
  active: boolean;
  attrType: string;
  attrClassify: string;
  error_code: string;
  error_message: string;
}

// 表单相关ref和reactive
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const resultLogicalOperator = ref("and");
const conditions_groupLogicalOperator = ref("and");
const topLevelLogicalOperator = ref("and");

// 添加一个标志位来区分是用户操作还是初始化赋值
const isInitializing = ref(false);

//基础属性下拉列表
const basicsLovOptions = ref([]);

//分类属性结果配置字段下拉列表
const attributePoolLovOptions = ref([]);

//条件配置字段下拉值
const conditionFieldOptions = ref([]);

//结果配置字段下拉值
const resultsFieldOptions = ref([]);

const classifyOptions = ref(Object.values(lovStore.classifyLov));
const filterNodeMethod = (value, data) => data.label.includes(value);
const handleNodeClick = (node) => {
  // 如果是最终节点，调用属性池接口
  if (node.isFinal) {
    attributePoolLovData(node.id);
  }
};

//选择树后基础属性下拉列表查询
const attributePoolLovData = async (categoryId: any) => {
  const res = await attributePoolLov({
    categoryId: categoryId,
  });
  attributePoolLovOptions.value = res.data;
};

// 表单数据
const ruleForm = reactive<RuleForm>({
  rule_code: "",
  description: "",
  priority: 1,
  active: true,
  attrType: "",
  attrClassify: "",
  error_code: "",
  error_message: "",
});

// 条件配置表格数据
const conditions_group = ref<RuleTableItem[]>([]);

// 生成唯一Key
const generateUniqueKey = () => {
  return Date.now().toString(36) + Math.random().toString(36).substring(2);
};

// 结果配置表格数据
const results = ref<RuleTableItem[]>([
  {
    key: generateUniqueKey(),
    field: "",
    operator: "",
    value: "",
    logical_operator: resultLogicalOperator.value,
    sub_conditions: [],
  },
]);

// ID计数器
let conditionIdCounter = ref(2);
let resultIdCounter = ref(2);

// 表单验证规则
const rules = reactive<FormRules<RuleForm>>({
  description: [{ required: true, message: "请输入描述信息", trigger: "blur" }],
  priority: [{ required: true, message: "请设置优先级", trigger: "change" }],
  attrType: [{ required: true, message: "请选择属性类型", trigger: "blur" }],
});

// 规则验证模块
const ruleValidations = {
  // 条件配置验证规则
  conditionRules: {
    field: [{ required: true, message: "请选择字段", trigger: "change" }],
    operator: [{ required: true, message: "请选择运算符", trigger: "change" }],
    value: [{ required: true, message: "请输入值", trigger: "blur" }],
  },

  // 结果配置验证规则
  resultRules: {
    field: [{ required: true, message: "请选择字段", trigger: "change" }],
    operator: [{ required: true, message: "请选择运算符", trigger: "change" }],
  },

  // 验证行数据
  validateRow(row: RuleTableItem, isCondition: boolean): boolean {
    const rules = isCondition ? this.conditionRules : this.resultRules;
    return Object.keys(rules).every((key) => {
      const ruleSet = rules[key];
      return ruleSet.every((rule) => {
        if (rule.required && !row[key]) {
          return false;
        }
        return true;
      });
    });
  },

  // 验证整个配置
  validateConfig(config: RuleTableItem[], isCondition: boolean): boolean {
    return config.every((row) => {
      let valid = this.validateRow(row, isCondition);
      if (valid && row.sub_conditions) {
        valid = this.validateConfig(row.sub_conditions, isCondition);
      }
      return valid;
    });
  },
};

// 下拉选项数据
const attrTypeOptions = [
  { value: "basicsSingle", label: "基础属性-单值规则" },
  { value: "basicsMulti", label: "基础属性-联动规则" },
  { value: "classifySingle", label: "分类属性-单值规则" },
  { value: "classifyMulti", label: "分类属性-联动规则" },
];

const operatorOptions = [
  { value: "contains", label: "包含" },
  { value: "not contains", label: "不包含" },
  { value: "start with", label: "以...开头" },
  { value: "end with", label: "以...结尾" },
  { value: "is", label: "是" },
  { value: "is not", label: "不是" },
  { value: "empty", label: "为空" },
  { value: "not empty", label: "不为空" },
  { value: "in", label: "在其中" },
  { value: "not in", label: "不在其中" },
  { value: "all of", label: "全部包含" },
  { value: "matches regex", label: "匹配正则" },
  { value: "not matches regex", label: "不匹配正则" },
  { value: "=", label: "等于" },
  { value: "≠", label: "不等于" },
  { value: ">", label: "大于" },
  { value: "<", label: "小于" },
  { value: "≥", label: "大于等于" },
  { value: "≤", label: "小于等于" },
  { value: "null", label: "为null" },
  { value: "not null", label: "不为null" },
  { value: "exists", label: "存在" },
  { value: "not exists", label: "不存在" },
];

const operatorString = [
  { value: "contains", label: "包含" },
  { value: "not contains", label: "不包含" },
  { value: "start with", label: "以...开头" },
  { value: "end with", label: "以...结尾" },
  { value: "is", label: "是" },
  { value: "is not", label: "不是" },
  { value: "empty", label: "为空" },
  { value: "not empty", label: "不为空" },
  { value: "in", label: "在其中" },
  { value: "not in", label: "不在其中" },
  { value: "all of", label: "全部包含" },
  { value: "matches regex", label: "匹配正则" },
  { value: "not matches regex", label: "不匹配正则" },
];

const operatorNumber = [
  { value: "=", label: "等于" },
  { value: "≠", label: "不等于" },
  { value: ">", label: "大于" },
  { value: "<", label: "小于" },
  { value: "≥", label: "大于等于" },
  { value: "≤", label: "小于等于" },
  { value: "in", label: "在其中" },
  { value: "not in", label: "不在其中" },
  { value: "null", label: "为空" },
  { value: "not null", label: "不为空" },
  // { value: 'exists', label: '存在' },
  // { value: 'not exists', label: '不存在' },
];

// 工具函数
const isMultiValueOperator = (operator: string): boolean => {
  return ["in", "not in"].includes(operator);
};

const stringToArray = (val: string | string[]): string[] => {
  if (Array.isArray(val)) return val;
  if (!val) return [];
  return val
    .split(",")
    .map((s) => s.trim())
    .filter(Boolean);
};

const arrayToString = (val: string | string[]): string => {
  if (Array.isArray(val)) return val.filter(Boolean).join(",");
  return val || "";
};

// 预处理显示数据
const processValuesForDisplay = (items: RuleTableItem[]): RuleTableItem[] => {
  return items.map((item) => ({
    ...item,
    // 只有当不是多值操作符时，才进行字符串化（如果需要的话）
    // 对于 'in'/'not in'，value 必须保持为数组以供 el-select 使用
    value: isMultiValueOperator(item.operator)
      ? Array.isArray(item.value)
        ? item.value
        : stringToArray(item.value) // 确保是数组
      : item.value,
    sub_conditions: item.sub_conditions
      ? processValuesForDisplay(item.sub_conditions)
      : undefined,
  }));
};

// 提交前处理
const prepareSubmitData = (nodes: RuleTableItem[]): any[] => {
  return nodes.map((node) => {
    const { key, sub_conditions, ...rest } = node;
    const newNode = { ...rest };
    if (isMultiValueOperator(newNode.operator)) {
      newNode.value = stringToArray(newNode.value as string);
    }
    if (sub_conditions?.length) {
      newNode.sub_conditions = prepareSubmitData(sub_conditions);
    }
    return newNode;
  });
};

// 根据字段类型获取运算符选项
const getOperatorOptions = (fieldValue: string, isCondition: boolean) => {
  if (!fieldValue) return operatorOptions;

  // 根据条件或结果配置选择不同的字段选项源
  const fieldOptions = isCondition
    ? conditionFieldOptions.value
    : resultsFieldOptions.value;

  // 查找字段对应的类型
  const field = fieldOptions.find((item: any) => item.value === fieldValue);

  if (field && field.dataType) {
    if (field.dataType === "文本型") {
      return operatorString;
    } else if (
      field.dataType === "整数型" ||
      field.dataType === "带单位的实数"
    ) {
      return operatorNumber;
    } else {
      return operatorOptions;
    }
  }

  // 默认返回所有运算符
  return operatorOptions;
};

// 根据字段值获取下拉选项
const getValueOptions = (fieldValue: string, isCondition: boolean) => {
  if (!fieldValue) return []; // 如果字段值为空，返回空数组

  // 根据条件或结果配置选择不同的字段选项源
  const fieldOptions = isCondition
    ? conditionFieldOptions.value
    : resultsFieldOptions.value;

  // 查找字段对应的类型
  const field = fieldOptions.find((item: any) => item.value === fieldValue);

  if (
    field &&
    (field.inputType === "下拉单选" || field.inputType === "下拉多选") &&
    field.children.length > 0
  ) {
    return field.children;
  }

  return [];
};

const shouldShowSelect = (field: string, isCondition: boolean): boolean => {
  const options = getValueOptions(field, isCondition);
  return Array.isArray(options) && options.length > 0;
};

// 计算是否显示条件配置
const showConditions = computed(() => {
  return !ruleForm.attrType.includes("Single");
});

// 计算属性分类是否禁用
const isAttrClassifyDisabled = computed(() => {
  return ruleForm.attrType.includes("basics");
});

const shouldShowSelectByOperatorAndField = (
  row: RuleTableItem,
  isCondition: boolean
): boolean => {
  if (!row?.field || !row?.operator) return false;

  const fieldOptions = isCondition
    ? conditionFieldOptions.value
    : resultsFieldOptions.value;
  const field = fieldOptions.find((item: any) => item.value === row.field);

  if (
    !field ||
    !field.children ||
    !Array.isArray(field.children) ||
    field.children.length === 0
  ) {
    return false;
  }

  const isDropdownType =
    field.inputType === "下拉单选" || field.inputType === "下拉多选";
  if (!isDropdownType) return false;

  // 只有 in / not in 显示为多选框，其他操作符显示为单选框
  // 无论是否多选，只要有下拉选项且是 in/not in 就显示下拉（多选或单选）
  return true;
};

// 条件配置表格合并单元格方法
const conditions_groupSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (showLogicalOperatorColumn) {
    if (column.property === "key") {
      // 如果是第一行且是顶级节点，则合并所有行
      if (rowIndex === 0 && !hasParent(row)) {
        return {
          rowspan: calculateTotalRows(conditions_group.value),
          colspan: 1,
        };
      } else {
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }
  }
  // 只处理运算符列
  if (column.property === "logical_operator") {
    // 如果是顶级行，不合并
    if (!hasParent(row)) {
      return {
        rowspan: 1,
        colspan: 1,
      };
    }

    // 获取父级行
    const parent = getParentRow(row);

    // 如果是父级行的第一个子行，则合并所有同级子行
    if (
      parent &&
      parent.sub_conditions &&
      parent.sub_conditions[0].key === row.key
    ) {
      return {
        rowspan: parent.sub_conditions.length,
        colspan: 1,
      };
    } else {
      // 其他子行不显示
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }

  // 其他列不合并
  return {
    rowspan: 1,
    colspan: 1,
  };
};

// 结果配置表格合并单元格方法
const resultSpanMethod = ({ row, column, rowIndex }) => {
  // 只处理运算符列
  if (column.property === "logical_operator") {
    // 如果是第一行且是顶级节点，则合并所有行
    if (rowIndex === 0 && !hasParent(row)) {
      return {
        rowspan: calculateTotalRows(results.value),
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};

// 计算表格总行数（包括子节点）
const calculateTotalRows = (nodes) => {
  let count = 0;
  const countRows = (items) => {
    items.forEach((item) => {
      count++;
      if (item.sub_conditions && item.sub_conditions.length > 0) {
        countRows(item.sub_conditions);
      }
    });
  };
  countRows(nodes);
  return count;
};

// 计算是否显示逻辑运算符列
const showLogicalOperatorColumn = computed(() => {
  const hasAnyParent = (nodes: RuleTableItem[]): boolean => {
    return nodes.some((node) => {
      if (node.sub_conditions?.length) return true;
      if (node.sub_conditions) return hasAnyParent(node.sub_conditions);
      return false;
    });
  };
  return hasAnyParent(conditions_group.value);
});

// 检查节点是否有父节点
const hasParent = (row: RuleTableItem): boolean => {
  if (!conditions_group.value) return false;

  const findParent = (nodes: RuleTableItem[], targetKey: string): boolean => {
    if (!nodes) return false;

    return nodes.some((node) => {
      if (node.sub_conditions?.some((child) => child.key === targetKey)) {
        return true;
      }
      if (node.sub_conditions) {
        return findParent(node.sub_conditions, targetKey);
      }
      return false;
    });
  };

  return findParent(conditions_group.value, row.key);
};

// 添加条件行
const addConditionRow = (record: RuleTableItem | null = null) => {
  const newRow: RuleTableItem = {
    key: generateUniqueKey(),
    field: "",
    operator: "",
    value: "",
    logical_operator: record
      ? record.sub_conditions?.[0]?.logical_operator || "and"
      : topLevelLogicalOperator.value,
    sub_conditions: [],
  };

  if (record) {
    // 确保新行的运算符与同级的其他行一致
    if (record.sub_conditions && record.sub_conditions.length > 0) {
      newRow.logical_operator = record.sub_conditions[0].logical_operator;
    }
    (record.sub_conditions ||= []).push(newRow);
  } else {
    conditions_group.value.push(newRow);
  }
};

// 更新所有顶级条件的运算符
const updateAllTopLevelConditions = () => {
  conditions_group.value.forEach((item) => {
    item.logical_operator = topLevelLogicalOperator.value;
  });
};

// 递归更新子条件运算符
const updateSubConditionsOperator = (
  nodes: RuleTableItem[],
  operator: string
) => {
  nodes.forEach((node) => {
    node.logical_operator = operator;
    if (node.sub_conditions && node.sub_conditions.length) {
      updateSubConditionsOperator(node.sub_conditions, operator);
    }
  });
};

// 获取父级行
const getParentRow = (row: RuleTableItem): RuleTableItem | null => {
  let parent = null;

  const findParent = (nodes: RuleTableItem[], target: RuleTableItem) => {
    for (const node of nodes) {
      if (node.sub_conditions?.includes(target)) {
        parent = node;
        return true;
      }
      if (node.sub_conditions && findParent(node.sub_conditions, target)) {
        return true;
      }
    }
    return false;
  };

  findParent(conditions_group.value, row);
  return parent;
};

// 更新子组内的所有条件
const updateSubGroupConditions = (row: RuleTableItem, operator: string) => {
  if (row.sub_conditions) {
    row.sub_conditions.forEach((item) => {
      item.logical_operator = operator;
    });
  }
};

// 递归更新所有结果行的逻辑运算符
function updateAllResultsLogicalOperator(
  nodes: RuleTableItem[],
  newVal: string
) {
  nodes.forEach((node) => {
    node.logical_operator = newVal;
    if (node.sub_conditions && node.sub_conditions.length > 0) {
      updateAllResultsLogicalOperator(node.sub_conditions, newVal);
    }
  });
}

// 添加结果行
const addResultRow = (record: RuleTableItem | null = null) => {
  const newRow: RuleTableItem = {
    key: generateUniqueKey(),
    field: "",
    operator: "",
    value: "",
    logical_operator: resultLogicalOperator.value,
    sub_conditions: [],
  };

  if (record) {
    (record.sub_conditions ||= []).push(newRow);
  } else {
    results.value.push(newRow);
  }
};

// 删除条件行
const delConditionRow = (row: RuleTableItem) => {
  deleteNode(conditions_group.value, row.key);
};

// 删除结果行
const delResultRow = (row: RuleTableItem) => {
  deleteNode(results.value, row.key);
};

// 通用递归删除逻辑
const deleteNode = (nodes: RuleTableItem[], key: string) => {
  for (let i = 0; i < nodes.length; i++) {
    if (nodes[i].key === key) {
      nodes.splice(i, 1);
      return true;
    }
    if (nodes[i].sub_conditions?.length) {
      const found = deleteNode(nodes[i].sub_conditions, key);
      if (found) return true;
    }
  }
  return false;
};

// 在提交表单时移除key的递归函数
const removeKeys = (nodes: RuleTableItem[]): any[] => {
  return nodes.map((node) => {
    // 创建新对象排除key属性
    const { key, sub_conditions, ...rest } = node;
    const newNode = { ...rest };

    // 递归处理子节点
    if (sub_conditions && sub_conditions.length > 0) {
      newNode.sub_conditions = removeKeys(sub_conditions);
    }

    return newNode;
  });
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      const isSingleRule = ruleForm.attrType.includes("Single");

      // 验证条件配置
      if (
        showConditions.value &&
        !ruleValidations.validateConfig(conditions_group.value, true)
      ) {
        XcmgMessage({
          message: "条件配置中存在未选择的字段或运算",
          type: "error",
          plain: true,
          showClose: true,
        });
        return;
      }

      //验证结果配置
      if (!ruleValidations.validateConfig(results.value, false)) {
        XcmgMessage({
          message: "结果配置中存在未选择的字段或运算",
          type: "error",
          plain: true,
          showClose: true,
        });
        return;
      }
      // 用 prepareSubmitData 统一处理
      const submitData = {
        ...ruleForm,
        conditions_group: isSingleRule
          ? []
          : prepareSubmitData(conditions_group.value),
        results: prepareSubmitData(results.value),
      };

      console.log("提交数据:", submitData);

      if (props.title === "新建") {
        await materialRuleAdd({
          ...submitData,
        });
        emit("queryMaterialRule");
        XcmgMessage({
          message: "新建成功",
          type: "success",
          plain: true,
          showClose: true,
        });
      } else {
        await materialRuleUpdata({
          uid: props.rowData.uid,
          ...submitData,
        });
        emit("queryMaterialRule");
        XcmgMessage({
          message: "保存成功",
          type: "success",
          plain: true,
          showClose: true,
        });
      }
    }
  });
};

// 保存表单
const handleSave = async (ruleFormRef) => {
  await submitForm(ruleFormRef);
};

// 保存并关闭表单
const handleSaveClose = async (ruleFormRef) => {
  submitForm(ruleFormRef);
  await toggleVisible();
};

const toggleVisible = () => {
  _visible.value = !_visible;
};

// 监听条件组逻辑运算符变化
watch(conditions_groupLogicalOperator, (newVal) => {
  updateAllResultsLogicalOperator(conditions_group.value, newVal);
});

// 监听结果逻辑运算符变化
watch(resultLogicalOperator, (newVal) => {
  updateAllResultsLogicalOperator(results.value, newVal);
});

// 监听属性类型变化 - 修复后的版本
watch(
  () => ruleForm.attrType,
  (newVal, oldVal) => {
    // 如果是初始化阶段，不执行重置逻辑
    if (isInitializing.value) return;

    // 只有当属性类型确实改变时才执行重置
    if (newVal !== oldVal) {
      ruleForm.attrClassify = "";
      resultsFieldOptions.value = [];

      if (newVal.includes("basics")) {
        resultsFieldOptions.value = basicsLovOptions.value;
      }

      if (newVal.includes("basicsMulti")) {
        conditionFieldOptions.value = basicsLovOptions.value;
      }

      if (oldVal) {
        if (newVal.includes("classify")) {
          results.value.forEach((item) => {
            item.field = "";
            item.operator = "";
            item.value = "";
          });
        }
      }
    }
  }
);

watch(
  () => attributePoolLovOptions.value,
  (newVal) => {
    if (ruleForm.attrType.includes("classifyMulti")) {
      conditionFieldOptions.value = [...basicsLovOptions.value, ...newVal];
    }
    if (ruleForm.attrType.includes("classify")) {
      //分类下拉值
      resultsFieldOptions.value = newVal;
    }
  }
);

watch(
  () => props.visible,
  async (newVal) => {
    if (newVal) {
      // 设置初始化标志
      isInitializing.value = true;

      resetForm();
      await basicsLovData();

      if (props.title === "编辑") {
        if (props.rowData && Object.keys(props.rowData).length > 0) {
          const { attrType, ...restData } = props.rowData;
          Object.assign(ruleForm, restData);
          ruleForm.attrType = attrType;

          // 预处理 conditions_group
          const processedConditions = processValuesForDisplay(
            props.rowData.conditions_group || []
          );
          conditions_group.value = processedConditions;

          // 预处理 results
          const processedResults = processValuesForDisplay(
            props.rowData.results || []
          );
          results.value = processedResults;

          if (attrType.includes("basics")) {
            resultsFieldOptions.value = basicsLovOptions.value;
          }

          if (attrType.includes("basicsMulti")) {
            conditionFieldOptions.value = basicsLovOptions.value;
          }

          if (attrType.includes("Single")) {
            addConditionRow();
          }

          if (attrType.includes("classify")) {
            attributePoolLovData(props.rowData.attrClassify);
          }
        }
      }

      // 延迟一小段时间后取消初始化标志
      setTimeout(() => {
        isInitializing.value = false;
      }, 100);
    }
  },
  { immediate: true }
);

// 重置表单方法
const resetForm = () => {
  // 重置条件配置表格
  conditions_group.value = [
    {
      key: generateUniqueKey(),
      field: "",
      operator: "",
      value: "",
      logical_operator: "and",
      sub_conditions: [],
    },
  ];
  conditionIdCounter.value = 2;

  // 重置结果配置表格
  results.value = [
    {
      key: generateUniqueKey(),
      field: "",
      operator: "",
      value: "",
      logical_operator: "and",
      sub_conditions: [],
    },
  ];
  resultIdCounter.value = 2;

  // 重置表单数据
  Object.assign(ruleForm, {
    rule_code: "",
    description: "",
    priority: 1,
    active: true,
    attrType: "",
    attrClassify: "",
    error_code: "",
    error_message: "",
  });

  // 重置运算符
  topLevelLogicalOperator.value = "and";
  resultLogicalOperator.value = "and";

  // 重置下拉选项
  basicsLovOptions.value = [];
  attributePoolLovOptions.value = [];
  conditionFieldOptions.value = [];
  resultsFieldOptions.value = [];
};

// 基础属性下拉列表查询
const basicsLovData = async () => {
  const res = await basicsLov({});
  basicsLovOptions.value = res.data;
};

// 组件挂载时初始化顶级条件运算符
onMounted(() => {
  addConditionRow();
  updateAllTopLevelConditions();
});
</script>

<style scoped>
:deep(.el-form-item__content) {
  display: flex;
}

.deploy :deep(.el-form-item__label) {
  width: 50.38px !important;
}

.deploy .colValue :deep(.el-form-item__label) {
  width: 34.38px !important;
}

:deep(.el-table td.el-table__cell) {
  border-bottom: 1.5px solid #ccc;
}

:deep(.cell) {
  display: flex;
}

:deep(.drawer-content) {
  padding-bottom: 0 !important;
}

.drawer-footer {
  width: calc(100% - 40px) !important;
  border-top: none !important;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

:deep(.el-table__expand-icon.el-table__expand-icon--expanded) {
  display: none;
}
</style>
